#include "multiprocess.hpp"

#include <gtkmm.h>
#include <libglademm.h>
#include "IRS.h"
#include <dirent.h>
#include <string>



void processfile(string filename,Config config){



    Glib::RefPtr<Gdk::Pixbuf> *loadimage = new Glib::RefPtr<Gdk::Pixbuf>;
    *loadimage = Gdk::Pixbuf::create_from_file(filename);

    Color_Image* colorimage=pixbuftoColor(loadimage);
    delete loadimage;

    Binary_Image* workimage = (Binary_Image*)colorimage->convert(Image::BINARY,0);
    if(config.invertimage)
        workimage->invert();
    delete colorimage;

    Binary_Image* seed;
    Binary_Image* body;
    Binary_Image* skel;

    preprocessing(workimage,&skel,&seed,&body,config.preprocessing);

    PositionMap* crossmap = new PositionMap(skel->getHeight(),skel->getWidth());
    Grey_Image* labelled = new Grey_Image(skel->getHeight(),skel->getWidth(),65500);
    RCData* rcdata = new RCData(skel->getHeight(),skel->getWidth());

    newlabelling(seed,skel,body,config.labellingoptions,crossmap,rcdata,rcdata,labelled);

    ContourExtractorBranch extractor;
    Contour* contour = extractor.getContour(labelled,crossmap);

    delete seed;
    delete body;
    delete skel;

    Color_Image* colorlabelled = (Color_Image*)labelled->convert(Image::COLOR,1);
    Glib::RefPtr<Gdk::Pixbuf> *saveimage = new Glib::RefPtr<Gdk::Pixbuf>;
    saveimage=imagetoPixbuf(colorlabelled);
    (*saveimage)->save(filename+"-rotuled.png","png");

    delete saveimage;
    delete labelled;
    delete colorlabelled;

    Glib::RefPtr<Gdk::Pixbuf> *saveimage2 = new Glib::RefPtr<Gdk::Pixbuf>;
    saveimage2=imagetoPixbuf(contour->img);
    (*saveimage2)->save(filename+"-contour.png","png");

    Color_Image* img2xcolor;
    Binary_Image* img2x;

    Glib::RefPtr<Gdk::Pixbuf> *imgscale = imagetoPixbuf(workimage);
    Glib::RefPtr<Gdk::Pixbuf> *imgscale2x = new Glib::RefPtr<Gdk::Pixbuf>;
    *imgscale2x = (*imgscale)->scale_simple(config.preprocessing.preprocessing_scale*workimage->getWidth(),config.preprocessing.preprocessing_scale*workimage->getHeight(),Gdk::INTERP_NEAREST);
    img2xcolor=pixbuftoColor(imgscale2x);
    img2x=(Binary_Image*)img2xcolor->convert(Image::BINARY,0);

    delete imgscale;
    delete imgscale2x;
    delete img2xcolor;

    Contour* expanded = contourexpand(contour,img2x);

    Glib::RefPtr<Gdk::Pixbuf> *saveimage3 = new Glib::RefPtr<Gdk::Pixbuf>;
    saveimage3=imagetoPixbuf(expanded->img);
    (*saveimage3)->save(filename+"-contour_exp.png","png");

    delete contour;
    delete expanded;
    delete workimage;

}


void multiprocess(string foldername,Config config){
    unsigned char isFile =0x8;
    DIR *dir;
    struct dirent *dirEntry;
    dir = opendir(foldername.c_str());

    while((dirEntry=readdir(dir))){
        if ( dirEntry->d_type == isFile){
            cout <<"Found a File : " << dirEntry->d_name << endl;
            processfile(foldername+'/'+dirEntry->d_name,config);
        }
    };
}
